package com.sikaryofficial.backend.controller;

import com.sikaryofficial.backend.service.brand.cache.BrandTasteCacheService;
import com.sikaryofficial.backend.utils.ProductUtil;
import com.sikaryofficial.common.core.constant.HttpStatus;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.HiResultUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.HiResult;
import com.sikaryofficial.system.api.RemoteQrCodeService;
import com.sikaryofficial.system.api.model.product.BrandTasteDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * 品牌口味Controller
 *
 * @author qinjinyuan
 * @date 2023-11-07
 */
@RestController
@RequestMapping("/brandTaste/qrcode")
@Api(tags = "产品二维码")
@Slf4j
public class BrandTasteQrcodeController extends BaseController {
    @Autowired
    private BrandTasteCacheService brandCacheService;
    @Autowired
    private RemoteQrCodeService remoteQrCodeService;

    /**
     * 通过HexId获取产品
     * <p>
     * param = 扫码url参数（HexStr(产品ID)+ seqno + 4位随机编码）
     */
    @GetMapping("/{param}")
    @ApiOperation("通过HexId获取产品")
    public HiResult<BrandTasteDTO> queryQrCodeByParam(@PathVariable("param") String param) {
        String[] params = param.split(ProductUtil.PARAM_SPLIT_KEY);
        BrandTasteDTO brandTasteDTO;
        if (params.length == 1) {
            brandTasteDTO = brandCacheService.getSignBrandTaste(ProductUtil.getIdByHexStr(params[0]));
        } else {
            // 逻辑：增加二维码param是否存在
            R<Boolean> existProductQrCode = remoteQrCodeService.existProductQrCode(param);
            if (Objects.isNull(existProductQrCode) || Boolean.FALSE.equals(existProductQrCode.getData())) {
                throw new ServiceException("the qrcode is not found:" + param, HttpStatus.ERROR);
            }
            brandTasteDTO = brandCacheService.brandByHexId(params[0]);
        }
        if (Objects.isNull(brandTasteDTO)) {
            throw new ServiceException("the product is not found:" + param, HttpStatus.ERROR);
        }
        return HiResultUtil.success(brandTasteDTO);
    }
}
